package com.sales.controller;

import com.sales.excption.SalesException;
import com.sales.service.UserService;
import com.sales.signUpReq.ResetPwdSignUpReq;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * Created by lihu on 2017/9/7.
 */
@Slf4j
@RestController
@RequestMapping(value = "/api/v1/sales", produces = "application/json;charset=utf-8")
public class UserController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    UserService userService;

    /**
     * 修改密码
     *
     * @param resetPwdSignUpReq
     * @param bindingResult
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/reset-pwd")
    public ResponseEntity updatePassword(@Valid @RequestBody ResetPwdSignUpReq resetPwdSignUpReq,
                                         BindingResult bindingResult) {
        try {
            //参数校验
            if (bindingResult.hasErrors()) {
                log.info("【修改密码】参数不正确, resetPwdSignUpReq={}", resetPwdSignUpReq);
                return new ResponseEntity(bindingResult.getFieldError().getDefaultMessage(),
                        HttpStatus.BAD_REQUEST);
            }

            //校验验证码
            String code = stringRedisTemplate.opsForValue().get(resetPwdSignUpReq.getMobile() + "_ACCOUNT");
            if (!StringUtils.equals(code, resetPwdSignUpReq.getVerifyCode())) {
                log.info("【验证码有误】, code={}", resetPwdSignUpReq.getVerifyCode());
                return new ResponseEntity("验证码有误",
                        HttpStatus.BAD_REQUEST);
            }
            //修改密码
            userService.updatePws(resetPwdSignUpReq.getMobile(), resetPwdSignUpReq.getPwd());
            return new ResponseEntity(HttpStatus.OK);
        } catch (SalesException ex) {
            log.error("updatePassword is error=>resetPwdSignUpReq:{}", resetPwdSignUpReq, ex);
            return new ResponseEntity(ex.getMessage(), HttpStatus.BAD_REQUEST);
        } catch (Exception ex) {
            log.error("updatePassword is error=>resetPwdSignUpReq:{}", resetPwdSignUpReq, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }
}
